package com.work.crops.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.work.crops.pojo.CropsInfoIndex;
import com.work.crops.pojo.CropsParam;
import com.work.crops.service.CropsIndexService;
import com.work.entity.PageResult;
import com.work.entity.Result;
import com.work.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cropsIndex")
public class CropsInfoIndexController {

    @Autowired
    private CropsIndexService cropsIndexService;

//    根据农作物id和生长阶段查询农作物指标
    @GetMapping("/{id}")
    public Result<List<CropsInfoIndex> > findById(@PathVariable("id") Integer id,@RequestParam("stage") String stage){
        try {
            List<CropsInfoIndex> list = cropsIndexService.findById(id,stage);
            return new Result(true, StatusCode.FIND_Ok,"查询成功",list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.FIND_ERROR,"查询失败");
        }
    }


//    分页条件查询
    @GetMapping("/findPage/{page}/{size}")
    public Result findByPage(@PathVariable Integer page,
                             @PathVariable Integer size,
                              CropsParam cropsParam){
        //        判断 条件对象是否为空
        Map map = JSON.parseObject(JSON.toJSONString(cropsParam), Map.class);
        Collection values = map.values();
        if (values.size() == 0){
//            如果长度为0增加标识
            cropsParam.setEmpty("alin");
        }

        try {
            PageInfo pageInfo = cropsIndexService.findByPage(page,size,cropsParam);
            PageResult pageResult = new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
            return new Result(true,StatusCode.FIND_Ok,"查询成功",pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.FIND_ERROR,"查询失败");
        }

    }

//    根据主键修改农作物数据
    @PutMapping("/edit")
    public Result updateById(@RequestBody CropsInfoIndex cropsInfoIndex){
        try {
            Integer row = cropsIndexService.updateById(cropsInfoIndex);
            return new Result(true,StatusCode.UPDATE_Ok,"修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.UPDATE_ERROR,"修改失败");
        }
    }

//    添加数据指标
    @PostMapping("/add")
    public Result add(@RequestBody CropsInfoIndex cropsInfoIndex){
        try {
            cropsIndexService.add(cropsInfoIndex);
            return new Result(true,StatusCode.ADD_OK,"添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ADD_ERROR,"添加失败");
        }
    }

}
